package com.xyx.yfy_site_msg.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyx.yfy_site_msg.system.entity.YfyMenu;
import com.xyx.yfy_site_msg.system.entity.YfyUser;
import com.xyx.yfy_site_msg.system.service.YfyMenuService;
import com.xyx.yfy_site_msg.system.utils.*;
import com.xyx.yfy_site_msg.system.vo.YfyMenuVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜单控制器
 * </p>
 *
 * @author xyx
 * @since 2020-11-09
 */
@Controller
@RestController
@RequestMapping("/menu")
public class YfyMenuController {

    @Autowired
    private YfyMenuService menuService;

    /*
     * 加载左侧所有可用菜单
     * 若登录用户为管理员（usertype=1），则查询全部菜单；若登录用户为普通用户（usertype=0），则查询相对应的菜单
     * 将usertype作为查询条件，关联yfy_user、yfy_uid_mid、yfy_menu三个数据表进行关联查询
     * */
    @RequestMapping("loadLeftMenuJson")
    @ResponseBody
    public DataGridView loadLeftMenuJson(YfyMenuVo menuVo) {
        QueryWrapper<YfyMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.TYPE_MENU);
        queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
        YfyUser user = (YfyUser) WebUtils.getSession().getAttribute("user");
        Integer usertype = user.getUsertype();
        List<YfyMenu> list;
        if (usertype.equals(Constast.USER_TYPE)) {
            list = menuService.loadAllUserMenu(usertype);
        } else {
            list = menuService.list(queryWrapper);
        }
        //需要将查到符合条件的菜单处理成有层级关系的json返回出去
        //格式化json串
        List<TreeNode> treeNodes = new ArrayList<>();
        for (YfyMenu menu : list) {
            Integer id = menu.getId();
            Integer pid = menu.getPid();
            String title = menu.getTitle();
            String icon = menu.getIcon();
            String href = menu.getHref();
            Boolean spread = menu.getOpen() == Constast.OPEN_TRUE ? true : false;
            treeNodes.add(new TreeNode(id, pid, title, icon, href, spread));
        }
        //使json串构造层级关系
        List<TreeNode> list2 = TreeNodeBuilder.build(treeNodes, 1);
        return new DataGridView(list2);
    }

    /*
     * 加载菜单管理左侧dtree
     * */
    @RequestMapping("loadLeftMenuDtreeJson")
    @ResponseBody
    public DataGridView loadMenuLeftJson(YfyMenuVo menuVo) {
        QueryWrapper<YfyMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.TYPE_MENU);
        List<YfyMenu> list = this.menuService.list(queryWrapper);
        ArrayList<TreeNode> treeNodes = new ArrayList<>();
        for (YfyMenu menu : list) {
            boolean spread = menu.getOpen() == 1 ? true : false;
            treeNodes.add(new TreeNode(menu.getId(), menu.getPid(), menu.getTitle(), spread));
        }
        return new DataGridView(treeNodes);
    }

    /*
     * 加载数据表格菜单json数据
     * */
    @RequestMapping("loadAllMenuJson")
    public DataGridView loadAllMenuJson(YfyMenuVo menuVo) {
        IPage<YfyMenu> page = new Page<>(menuVo.getPage(), menuVo.getLimit());
        QueryWrapper<YfyMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(menuVo.getId() != null, "id", menuVo.getId()).or().eq(menuVo.getId() != null, "pid", menuVo.getId());
        queryWrapper.like(StringUtils.isNotBlank(menuVo.getTitle()), "title", menuVo.getTitle());
        queryWrapper.eq("type", Constast.TYPE_MENU);
        queryWrapper.orderByAsc("num");
        this.menuService.page(page, queryWrapper);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    /*
     * 添加菜单接口
     * */
    @RequestMapping("addMenu")
    public ResultObj addMenu(YfyMenuVo menuVo) {
        try {
            this.menuService.save(menuVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /*
     * 修改菜单数据
     * */
    @RequestMapping("updateMenu")
    public ResultObj updateMenu(YfyMenuVo menuVo) {
        try {
            this.menuService.updateById(menuVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /*
     * 删除菜单
     * */
    @RequestMapping("deleteMenu")
    public ResultObj deleteMenu(Integer id) {
        try {
            this.menuService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /*
     * 加载最大排序吗
     * */
    @RequestMapping("loadMenuMaxNum")
    public Map<String, Object> loadMenuMaxNum() {
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<YfyMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("num");
        List<YfyMenu> list = this.menuService.list(queryWrapper);
        if (list.size() > 0) {
            map.put("value", list.get(0).getNum() + 1);
        } else {
            map.put("value", 1);
        }
        return map;
    }
}

